import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export interface User {
  id: string
  username: string
  email?: string
  avatar?: string
  role?: string
  createdAt?: string
  lastLoginAt?: string
}

export interface AuthState {
  user: User | null
  token: string | null
  isAuthenticated: boolean
}

export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref<User | null>(null)
  const token = ref<string | null>(null)
  const isAuthenticated = computed(() => !!token.value && !!user.value)

  // 从本地存储初始化状态
  const initializeFromStorage = () => {
    try {
      const storedToken = localStorage.getItem('token')
      const storedUser = localStorage.getItem('user')

      if (storedToken && storedUser) {
        token.value = storedToken
        user.value = JSON.parse(storedUser)
      }
    } catch (error) {
      console.error('Failed to initialize user state from storage:', error)
      clearUserData()
    }
  }

  // 设置用户信息
  const setUser = (userData: User, authToken: string) => {
    user.value = userData
    token.value = authToken

    // 保存到本地存储
    localStorage.setItem('token', authToken)
    localStorage.setItem('user', JSON.stringify(userData))
  }

  // 更新用户信息
  const updateUser = (userData: Partial<User>) => {
    if (user.value) {
      user.value = { ...user.value, ...userData }
      // 更新本地存储
      localStorage.setItem('user', JSON.stringify(user.value))
    }
  }

  // 清除用户数据
  const clearUserData = () => {
    user.value = null
    token.value = null

    // 清除本地存储
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  // 登出
  const logout = () => {
    clearUserData()
  }

  // 检查token是否有效
  const isTokenValid = () => {
    if (!token.value) return false

    try {
      // 这里可以添加token过期检查逻辑
      // 例如解析JWT token的过期时间
      return true
    } catch {
      return false
    }
  }

  // 获取用户头像
  const getUserAvatar = computed(() => {
    return user.value?.avatar || getDefaultAvatar()
  })

  // 默认头像
  const getDefaultAvatar = () => {
    return 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><circle cx="32" cy="32" r="32" fill="%23e3f2fd"/><text x="50%" y="54%" text-anchor="middle" font-size="28" fill="%231976d2">👤</text></svg>'
  }

  return {
    // 状态
    user,
    token,
    isAuthenticated,

    // 方法
    setUser,
    updateUser,
    clearUserData,
    logout,
    isTokenValid,
    initializeFromStorage,

    // 计算属性
    getUserAvatar,
  }
})
